// import { Constant } from "../../../../lib/app_constant";
// import Log from "../../../../lib/common/Log";
// import { JL_RCSP, JL_RCSPOP } from "../../../../lib/lib_rcsp";
// import { rcspManage } from "../../../../lib/rcsp/RcspBluetoothAdapter";
// import { rcspDeviceOpSet } from "../../../../lib/rcsp/RCSPDeviceManager";
// import { RcspManagerCallback } from "../../../../lib/rcsp/RcspManager";

import { OPAlarm } from "../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
import { RCSPOpAlarm } from "../../../lib/rcsp-impl/rcsp";
import { authManager } from "../../../api/auth-manager";
import api from "../../../api/index";
const i18n = require('../../../i18n/index');

// let _RCSPWrapperEventCallback: RcspManagerCallback | undefined
// let _RCSPWrapper: JL_RCSPOP.RcspOperateWrapper | undefined
// let _RcspOpImpl: JL_RCSP.RcspImpl | undefined
// let _Device: JL_RCSP.BtDevice | undefined
let opAlarm: OPAlarm.IOperateAlarm | undefined
const TAG = "pageAlarmClock"
const DEBUG = true
let operaterEventCallbackAlarm: OPAlarm.OperaterEventCallbackAlarm | undefined
// pages/pageMultiMedia/pageAlarmClock/pageAlarmClock.ts
Page({

    /**
     * 页面的初始数据
     */
    data: {
        l10n: {},
        operationList: [{
            type: "warn",
            text: '删除',
        }],
        alarmBeans: new Array<OPAlarm.AlarmBean>(),
    },
    // operaterEventCallbackAlarm: OPAlarm.OperaterEventCallbackAlarm.prototype,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.ensureLang();
        this.updateTexts();
        // _RCSPWrapper = rcspManage.getCurrentRcspOperateWrapper()!.wrapper;
        // _RcspOpImpl = _RCSPWrapper.getRcspImpl()
        // _Device = _RcspOpImpl.getUsingDevice()!
        // _RCSPWrapperEventCallback = {
        //     onSwitchUseDeviceEvent: (_device) => {
        //         wx.navigateBack({ delta: getCurrentPages().length })
        //     }, onAdvInfoEvent: (_device, _advInfo) => {

        //     }, onMandatoryUpgradeEvent: (_device) => {

        //     }, onRcspInitEvent: (_device, _isInit) => {

        //     }, onDeviceDisconnectEvent: (_device) => {
        //         },
        // }
        // rcspManage.addCallback(_RCSPWrapperEventCallback)
        // this.operaterEventCallbackAlarm = new JL_RCSPOP.OPAlarm.OperateEventCallbackAlarm()
        // this.operaterEventCallbackAlarm.onEvent = (event) => {
        //     switch (event.type) {
        //         case 'AlarmBeanListChange':
        //             if (event.AlarmBeanListChange?.alarmBeanList) {
        //                 this.setData({
        //                     alarmBeans: event.AlarmBeanListChange?.alarmBeanList
        //             })
        //             }
        //             break;

        //         default:
        //             break;
        //     }
        // }
        // rcspDeviceOpSet.OpAlarm?.registerEventCallback(this.operaterEventCallbackAlarm)
        operaterEventCallbackAlarm = {
            onEvent: (_event) => {
                if (_event.type === 'AlarmBeanListChange') {
                    if (_event.AlarmBeanListChange?.alarmBeanList) {
                        this.setData({
                            alarmBeans: _event.AlarmBeanListChange?.alarmBeanList
                        })
                    }
                }
            }
        }
        opAlarm = RCSPOpAlarm
        console.log("RCSPOpAlarm",RCSPOpAlarm);
        
        opAlarm?.registerEventCallback(operaterEventCallbackAlarm)
        
        // 初始化用户信息
        this.initUserInfo();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.ensureLang();
        this.updateTexts();
        // rcspDeviceOpSet.OpAlarm?.getAlarmBeanList({ isRealTime: true }).then((res) => {
        //     this.setData({
        //         alarmBeans: res
        //     })
        // })
        // rcspDeviceOpSet.OpAlarm?.getAlarmDefaultBells().then((res) => {
        //     // DEBUG && Log.d(TAG, "getAlarmDefaultBells" + JSON.stringify(res))
        // })
        RCSPOpAlarm?.readAlarmList().then((res) => {
            const list = (res?.alarmBeanList || []).map((b: any) => ({
                ...b,
                repeatText: this.formatRepeat(b.repeatMode)
            }));
            this.setData({ alarmBeans: list })
        })
        RCSPOpAlarm?.getAlarmDefaultBells();
        
        // 刷新用户信息
        this.refreshUserInfo();
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('闹钟管理页面卸载，返回设备页面');
        // if (_RCSPWrapperEventCallback) {
        //     rcspManage.removeCallback(_RCSPWrapperEventCallback)
        // }
        // rcspDeviceOpSet.OpAlarm?.unregisterEventCallback(this.operaterEventCallbackAlarm)
        if (operaterEventCallbackAlarm) {
            RCSPOpAlarm?.unregisterEventCallback(operaterEventCallbackAlarm)            
        }
    },
    onEmptClick() { },
    onDeleteAlarm(e: any) {
        const item: OPAlarm.AlarmBean = e.currentTarget.dataset.item
        if (!item) {
            console.error('删除闹钟失败：未找到闹钟数据')
            return
        }
        
        // 显示确认删除对话框
        wx.showModal({
            title: i18n.t('alarm.deleteConfirmTitle'),
            content: i18n.t('alarm.deleteConfirmContent', { name: item.name || i18n.t('alarm.defaultName') }),
            confirmText: i18n.t('alarm.delete'),
            confirmColor: '#ef4444',
            cancelText: i18n.t('alarm.cancel'),
            success: (res) => {
                if (res.confirm) {
                    // 显示加载提示
                    wx.showLoading({
                        title: i18n.t('alarm.deleting'),
                        mask: true
                    })
                    
                    RCSPOpAlarm?.deleteAlarm([item]).then((deleteRes) => {
                        wx.hideLoading()
                        if (deleteRes == true) {
                            // 删除成功后刷新列表
                            RCSPOpAlarm?.readAlarmList().then((res) => {
                                const list = (res?.alarmBeanList || []).map((b: any) => ({
                                    ...b,
                                    repeatText: this.formatRepeat(b.repeatMode)
                                }));
                                this.setData({
                                    alarmBeans: list
                                })
                            })
                            wx.showToast({
                                title: i18n.t('alarm.deleteSuccess'),
                                icon: 'success',
                                duration: 1500
                            })
                        } else {
                            wx.showToast({
                                title: i18n.t('alarm.deleteFailed'),
                                icon: 'error',
                                duration: 2000
                            })
                        }
                    }).catch((error) => {
                        wx.hideLoading()
                        console.error('删除闹钟失败:', error)
                        wx.showToast({
                            title: i18n.t('alarm.deleteFailed'),
                            icon: 'error',
                            duration: 2000
                        })
                    })
                }
            }
        })
    },
    onSwitchChange(e: any) {
        const checked = e.detail.value
        const bean = e.currentTarget.dataset.bean
        if (RCSPOpAlarm == undefined) return
        bean.open = checked
        // DEBUG && Log.d(TAG, "onSwitchChange ", bean);
        RCSPOpAlarm.addOrModifyAlarm([bean]).then((res) => {
            if (res) {
                RCSPOpAlarm?.readAlarmList()
            }
        })
    },
    onEditAlarmBean(e: any) {
        const bean = e.currentTarget.dataset.bean
        if (RCSPOpAlarm == undefined) return
        // const mask = 0
        // RCSPOpAlarm.readAlarmBellArgs(mask).then(() =? {

        // })
        // DEBUG && Log.d(TAG, "onEditAlarmBean ", bean);
        RCSPOpAlarm.getAlarmVersion().then((version) => {
            wx.navigateTo({
                url: '/pages/function_test/pageAlarmClock/pageAlarmDetail/index?alarmtype=1',
                events: {
                }, success: function (res) {
                    res.eventChannel.emit('alarmBean', { data: bean })
                }
            })
        })
    },
    onAddNewAlarmBean() {
        if (RCSPOpAlarm == undefined) return
        if (this.data.alarmBeans.length > 4) {
            wx.showToast({ title: i18n.t('alarm.limitReached') })
            return
        }
        
        // 显示同步时间提示
        wx.showLoading({
            title: i18n.t('alarm.syncTimeLoading'),
            mask: true
        })
        
        // 先同步时间，再创建闹钟
        RCSPOpAlarm.syncTime(new Date()).then(() => {
            wx.hideLoading()
            console.log("时间同步成功，开始创建闹钟")
            // 时间同步成功后，继续创建闹钟的逻辑
            if (RCSPOpAlarm) {
                RCSPOpAlarm.getAlarmVersion().then((version) => {
                    let useIndex = 0
                    for (let index = 0; index < 5; index++) {
                        let isCanUse = true
                        for (let j = 0; j < this.data.alarmBeans.length; j++) {
                            const element = this.data.alarmBeans[j];
                            if (index == element.index) {
                                isCanUse = false
                                break
                            }
                        }
                        if (isCanUse) {
                            useIndex = index
                            break
                        }
                    }
                    const date = new Date()
                    const newBean = new OPAlarm.AlarmBean()
                    newBean.index = useIndex//todo 要实际的
                    newBean.name = i18n.t('alarm.defaultName')
                    newBean.hour = date.getHours()
                    newBean.min = date.getMinutes()
                    newBean.repeatMode = 0
                    // newBean.reserved
                    newBean.open = true
                    newBean.bellType = 0
                    newBean.bellCluster = 0
                    newBean.version = version//todo 这里要获取当前实际的
                    wx.navigateTo({
                        url: '/pages/function_test/pageAlarmClock/pageAlarmDetail/index?alarmtype=0',
                        events: {
                        }, success: function (res) {
                            res.eventChannel.emit('alarmBean', { data: newBean })
                        }
                    })
                })
            }
        }).catch(() => {
            wx.hideLoading()
            wx.showToast({
                title: i18n.t('alarm.syncTimeFailed'),
                icon: 'error',
                duration: 2000
            })
        })
    },
    onSyncTime() {
        if (RCSPOpAlarm == undefined) return
        RCSPOpAlarm.syncTime(new Date()).then(() => {
            wx.showToast({
                title: i18n.t('device.syncSuccess'),
                icon: 'success',
            })
        }).catch(() => {
            wx.showToast({
                title: i18n.t('device.syncFailed'),
                icon: 'error',
            })
        })
    },

    /**
     * 批量同步所有闹钟到服务器
     */
    async syncAllAlarmsToServer() {
        try {
            // 检查登录状态
            if (!authManager.isAuthenticated()) {
                wx.showToast({
                    title: i18n.t('alarm.needLogin'),
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            wx.showLoading({
                title: i18n.t('device.loadingDeviceData'),
                mask: true
            });

            // 获取当前设备的所有闹钟
            const alarmListResponse = await RCSPOpAlarm?.readAlarmList();
            if (!alarmListResponse?.alarmBeanList) {
                wx.hideLoading();
                wx.showToast({
                    title: i18n.t('device.stateFailed'),
                    icon: 'error',
                    duration: 2000
                });
                return;
            }

            const alarms = alarmListResponse.alarmBeanList;
            if (alarms.length === 0) {
                wx.hideLoading();
                wx.showToast({
                    title: i18n.t('alarm.emptyText'),
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            const currentUser = authManager.getCurrentUser();
            if (!currentUser?.id) {
                wx.hideLoading();
                wx.showToast({
                    title: i18n.t('device.stateFailed'),
                    icon: 'error',
                    duration: 2000
                });
                return;
            }

            // 构建批量同步数据
            const batchAlarms = alarms.map(alarm => ({
                userId: currentUser.id,
                deviceId: 1, // 默认设备ID
                name: alarm.name || i18n.t('alarm.defaultName'),
                hour: alarm.hour || 0,
                minute: alarm.min || 0,
                repeatMode: alarm.repeatMode || 0,
                isEnabled: alarm.open || true,
                bellType: alarm.bellType || 0,
                bellName: alarm.bellName || '',
                status: 1
            }));

            console.log('批量同步闹钟到服务器:', batchAlarms);

            // 调用批量同步API
            const response = await api.post('/api/alarm/sync/batch', batchAlarms);
            
            wx.hideLoading();
            
            if (response?.data?.code === 0) {
                wx.showToast({
                    title: i18n.t('device.syncToast'),
                    icon: 'success',
                    duration: 2000
                });
            } else {
                wx.showToast({
                    title: i18n.t('device.syncToastFailed'),
                    icon: 'error',
                    duration: 2000
                });
            }

        } catch (error: any) {
            wx.hideLoading();
            console.error('批量同步闹钟到服务器异常:', error);
            wx.showToast({
                title: i18n.t('device.syncToastFailed'),
                icon: 'error',
                duration: 2000
            });
        }
    },

    /**
     * 初始化用户信息
     */
    async initUserInfo() {
        try {
            // 尝试从API获取用户信息
            const response = await api.getUserInfo();
            
            // 添加详细的响应日志
            console.log('�� 闹钟主页面 - API响应详情:', {
                statusCode: response?.statusCode,
                responseData: response?.data,
                code: response?.data?.code,
                message: response?.data?.message,
                hasData: !!response?.data?.data,
                dataType: typeof response?.data?.data,
                dataKeys: response?.data?.data ? Object.keys(response?.data?.data) : []
            });
            
            // 检查响应结构 - 修复：处理code可能是字符串的情况
            const responseCode = response?.data?.code;
            const isSuccess = responseCode === 0 || responseCode === "0" || responseCode === 200 || responseCode === "200";
            
            if (isSuccess && response.data.data) {
                const userInfo = response.data.data;
                console.log('✅ 闹钟主页面 - 成功获取用户信息:', userInfo);
                
                // 保存到本地存储
                wx.setStorageSync('userInfo', userInfo);
                if (userInfo.id) {
                    wx.setStorageSync('userId', userInfo.id);
                }
                
                // 更新认证管理器
                if (authManager) {
                    // 这里可以调用authManager的更新方法，如果有的话
                    console.log('用户信息已更新到本地存储');
                }
            } else if (isSuccess && !response.data.data) {
                // 如果code是成功但没有data，可能是空数据的情况
                console.warn('⚠️ 闹钟主页面 - API返回成功但无用户数据，可能用户未登录或数据为空');
                
                // 尝试从响应中查找用户信息
                const possibleUserInfo = response.data.user || response.data.userInfo || response.data;
                if (possibleUserInfo && (possibleUserInfo.id || possibleUserInfo.userId)) {
                    console.log('🔍 闹钟主页面 - 从响应中提取到可能的用户信息:', possibleUserInfo);
                    const userInfo = {
                        id: possibleUserInfo.id || possibleUserInfo.userId,
                        nickname: possibleUserInfo.nickname || possibleUserInfo.username || '智能水杯用户',
                        username: possibleUserInfo.username || possibleUserInfo.nickname
                    };
                    
                    wx.setStorageSync('userInfo', userInfo);
                    wx.setStorageSync('userId', userInfo.id);
                    console.log('✅ 闹钟主页面 - 已保存提取的用户信息');
                }
            } else {
                console.warn('⚠️ 闹钟主页面 - 获取用户信息失败:', {
                    code: response?.data?.code,
                    message: response?.data?.message,
                    fullResponse: response?.data
                });
            }
        } catch (error) {
            console.error('❌ 闹钟主页面 - 初始化用户信息异常:', error);
        }
    },

    /**
     * 刷新用户信息
     */
    async refreshUserInfo() {
        try {
            // 检查本地是否有用户信息
            const storedUserInfo = wx.getStorageSync('userInfo');
            const storedUserId = wx.getStorageSync('userId');
            
            if (!storedUserInfo || !storedUserId) {
                console.log('🔄 本地用户信息缺失，重新获取');
                await this.initUserInfo();
            } else {
                console.log('✅ 本地用户信息完整:', { userId: storedUserId, hasUserInfo: !!storedUserInfo });
            }
        } catch (error) {
            console.error('❌ 刷新用户信息失败:', error);
        }
    },
    ensureLang() {
      try {
        const saved = wx.getStorageSync('app:lang');
        const cur = i18n.getLang && i18n.getLang();
        if (saved && saved !== cur && i18n.setLang) i18n.setLang(saved);
      } catch (_) {}
    },

    updateTexts() {
      const t = (k: string, p?: any) => i18n.t('alarm.' + k, p);
      this.setData({
        l10n: {
          title: t('title'),
          listTitle: t('listTitle'),
          emptyText: t('emptyText'),
          opsTitle: t('opsTitle'),
          createTitle: t('createTitle'),
          createDesc: t('createDesc'),
          createBtn: t('createBtn'),
          delete: t('delete')
        },
        operationList: [{ type: 'warn', text: t('delete') }]
      });
      wx.setNavigationBarTitle({ title: t('title') });
    },

    formatRepeat(mode: number) {
        const t = (k: string) => i18n.t('alarm.' + k);
        if (mode === 0) return t('repeatOnce');
        if (mode === 1) return t('repeatEveryday');
        if (mode === 62) return t('repeatWorkday');
        const arr: string[] = [];
        if (((mode >> (1)) & 1) === 1) arr.push(t('weekMon'));
        if (((mode >> (2)) & 1) === 1) arr.push(t('weekTue'));
        if (((mode >> (3)) & 1) === 1) arr.push(t('weekWed'));
        if (((mode >> (4)) & 1) === 1) arr.push(t('weekThu'));
        if (((mode >> (5)) & 1) === 1) arr.push(t('weekFri'));
        if (((mode >> (6)) & 1) === 1) arr.push(t('weekSat'));
        if (((mode >> (7)) & 1) === 1) arr.push(t('weekSun'));
        return arr.join(' ');
    }
})